<template>
  <div class="login-container">
    <!-- 导航栏 -->
    <van-nav-bar title="登录" class="my-nav-bar" />
    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请填写手机号"
        required
        :rules="[
          { required: true, message: '请填写手机号' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不正确'
          }
        ]"
      />
      <van-field
        v-model="code"
        type=""
        name="code"
        label="验证码"
        placeholder="请填写验证码"
        required
        :rules="[
          { required: true, message: '请填写验证码' },
          { pattern: /\d{6}/, message: '验证码格式不正确' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="登录中"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
// 导入api方法
import { userLogin } from '../../api/login'
// 导入token
import { saveTkone } from '../../utils/token'
export default {
  data () {
    return {
      // 手机号
      mobile: '17683737376',
      // 验证码
      code: '246810',
      // 是否加载样式
      isLoading: false
    }
  },
  methods: {
    onSubmit (values) {
      // 开启loading
      this.isLoading = true
      // console.log('submit', values)
      userLogin(values)
        .then(res => {
          // 保存token
          saveTkone(res.data.data)

          setTimeout(() => {
            this.isLoading = false
            this.$toast({
              message: '登陆成功!',
              icon: 'smile-o'
            })
            // 判断是否有 redirect参数（是否从别的页面强制登录）
            const redirect = this.$route.query.redirect
            if (redirect) {
              // 有就登录完成返回对应页面
              return this.$router.push({ path: redirect })
            }
            // 没有就是首页
            this.$router.push({ path: '/home' })
          }, 300)
        })
        .catch(errRes => {
          setTimeout(() => {
            this.isLoading = false
            this.$toast({
              message: '登录失败',
              icon: 'warning-o'
            })
          }, 300)
        })
    }
  }
}
</script>
<style lang="less">
.login-container {
  .van-nav-bar {
    background-color: #3196fa;
    .van-nav-bar__title {
      color: #fff;
    }
  }
}
</style>
